package com.ruoyi.function.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.json.FastjsonUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.function.domain.Garage;
import com.ruoyi.function.domain.Technician;
import com.ruoyi.function.domain.vo.ChatRecordVo;
import com.ruoyi.function.domain.vo.UserChatVo;
import com.ruoyi.function.mapper.GarageMapper;
import com.ruoyi.function.mapper.TechnicianMapper;
import com.ruoyi.function.service.IGarageService;
import com.ruoyi.function.service.ITechnicianService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.function.mapper.ChatRecordMapper;
import com.ruoyi.function.domain.ChatRecord;
import com.ruoyi.function.service.IChatRecordService;

import static com.ruoyi.common.utils.PageUtils.startPage;

/**
 * -- 聊天记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-26
 */
@Service
public class ChatRecordServiceImpl implements IChatRecordService {
    @Autowired
    private ChatRecordMapper chatRecordMapper;
    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private TechnicianMapper technicianMapper;

    @Autowired
    private GarageMapper garageMapper;

    /**
     * 查询-- 聊天记录
     *
     * @param id -- 聊天记录主键
     * @return -- 聊天记录
     */
    @Override
    public ChatRecord selectChatRecordById(String id) {
        return chatRecordMapper.selectChatRecordById(id);
    }

    /**
     * 查询-- 聊天记录列表
     *
     * @param chatRecord -- 聊天记录
     * @return -- 聊天记录
     */
    @Override
    public List<ChatRecord> selectChatRecordList(ChatRecord chatRecord) {
        return chatRecordMapper.selectChatRecordList(chatRecord);
    }

    /**
     * 新增-- 聊天记录
     *
     * @param chatRecord -- 聊天记录
     * @return 结果
     */
    @Override
    public int insertChatRecord(ChatRecord chatRecord) {
        SysUser user = userMapper.selectUserById(chatRecord.getSenderId());
        if (user != null) {
            chatRecord.setSelf(userToStringRecord(user));
        }
        long l = Long.parseLong(chatRecord.getReceiverId());
        SysUser user1 = userMapper.selectUserById(l);
        if (user1 != null) {
            chatRecord.setTarget(userToStringRecord(user1));
        }
        chatRecord.setCreateTime(DateUtils.getNowDate());
        return chatRecordMapper.insertChatRecord(chatRecord);
    }

    private String userToStringRecord(SysUser user) {
        UserChatVo userChatVo = new UserChatVo();
        if (user.getUserId() == 1L) {
            userChatVo.setName(user.getNickName());
            userChatVo.setAvatar(user.getAvatar());
        } else if (user.getCurrentRole() == 1L) {
            userChatVo.setName(user.getNickName());
            userChatVo.setAvatar(user.getAvatar());
        } else if (user.getCurrentRole() == 2L) {
            Technician technician = technicianMapper.selectByUserId(user.getUserId());
            if (technician != null) {
                userChatVo.setName(technician.getName());
                userChatVo.setAvatar(technician.getAvatar());
            }

        } else if (user.getCurrentRole() == 3l) {
            Garage garage = garageMapper.selectByUserId(user.getUserId());
            if (garage != null) {
                userChatVo.setName(garage.getGarageName());
                userChatVo.setAvatar(garage.getAvatar());
            }
        }
        return FastjsonUtils.toJson(userChatVo);// userChatVo.toString();
    }

    /**
     * 修改-- 聊天记录
     *
     * @param chatRecord -- 聊天记录
     * @return 结果
     */
    @Override
    public int updateChatRecord(ChatRecord chatRecord) {
        chatRecord.setUpdateTime(DateUtils.getNowDate());
        return chatRecordMapper.updateChatRecord(chatRecord);
    }

    /**
     * 批量删除-- 聊天记录
     *
     * @param ids 需要删除的-- 聊天记录主键
     * @return 结果
     */
    @Override
    public int deleteChatRecordByIds(String[] ids) {
        return chatRecordMapper.deleteChatRecordByIds(ids);
    }

    /**
     * 删除-- 聊天记录信息
     *
     * @param id -- 聊天记录主键
     * @return 结果
     */
    @Override
    public int deleteChatRecordById(String id) {
        return chatRecordMapper.deleteChatRecordById(id);
    }

    @Override
    public List<ChatRecordVo> getHistory(Long senderId, Long receiverId, String userType) {
        List<ChatRecord> history = chatRecordMapper.getHistory(senderId, receiverId, userType);
        List<ChatRecordVo> list = new ArrayList<>();
        for (ChatRecord chatRecord : history) {
            ChatRecordVo chatRecordVo = new ChatRecordVo();
            BeanUtils.copyProperties(chatRecord, chatRecordVo);
            chatRecordVo.setSelfUse(FastjsonUtils.fromJson(chatRecord.getSelf(), UserChatVo.class));
            chatRecordVo.setTargetUse(FastjsonUtils.fromJson(chatRecord.getTarget(), UserChatVo.class));
            list.add(chatRecordVo);
        }
        // 修改状态为已读
        ChatRecord chatRecord = new ChatRecord();
        chatRecord.setSenderId(senderId);
        chatRecord.setReceiverId(String.valueOf(receiverId));
        chatRecord.setUserType(userType);
        int i = chatRecordMapper.updateIsRead(chatRecord);
        return list;
    }

    @Override
    public List<ChatRecordVo> getCurrentUserChatRecords( Long currentRole) {
        //参数不能为空
        if (currentRole == null){
            throw new IllegalArgumentException("角色不能为空");
        }
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
            startPage();
            //获取当前用户聊天记录
            List<ChatRecord> currentUserChatRecords = chatRecordMapper.getCurrentUserChatRecords(userId, currentRole);
            List<ChatRecordVo> list = new ArrayList<>();
            for (ChatRecord chatRecord : currentUserChatRecords) {
                ChatRecordVo chatRecordVo = new ChatRecordVo();
                BeanUtils.copyProperties(chatRecord, chatRecordVo);
                chatRecordVo.setSelfUse(FastjsonUtils.fromJson(chatRecord.getSelf(), UserChatVo.class));
                chatRecordVo.setTargetUse(FastjsonUtils.fromJson(chatRecord.getTarget(), UserChatVo.class));
                int unreadCount = chatRecordMapper.chatRecordMapper(chatRecord);
                chatRecordVo.setUnreadCount(unreadCount);
                list.add(chatRecordVo);
            }
            return list;

    }

    @Override
    public int read(ChatRecord chatRecord) {
        if (chatRecord == null || chatRecord.getId() == null) {
            throw new IllegalArgumentException("聊天记录ID不能为空");
        }
        ChatRecord chatRecord1 = chatRecordMapper.selectChatRecordById(chatRecord.getId());
        int a = 0;
        if (StringUtils.isNotNull(chatRecord1)) {
            a = chatRecordMapper.updateIsRead(chatRecord1);
        } else {
            throw new IllegalArgumentException("聊天记录不存在");
        }
        return a;
    }

    @Override
    public int getUnreadCount(Long currentRole) {
        //currentRole不能为空
        if (currentRole == null) {
            throw new IllegalArgumentException("角色不能为空");
        }
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
        SysUser user = userMapper.selectUserById(userId);
        if (StringUtils.isNull(user)) {
            return 0;
        }
        return chatRecordMapper.getUnreadCount(userId, currentRole);

    }
}
